<?php

namespace App\Utils;

use Illuminate\Support\Facades\Log;

class NumberToChinese
{
    protected $appends = ['amount_display'];

    public static function convert($number)
    {
        $number = sprintf('%.2f', floatval($number));
        list($integer, $fraction) = explode('.', $number);

        $result = self::convertInteger($integer) . '元';
        $result .= self::convertFraction($fraction);

        return $result;
    }

    private static function convertInteger($number)
    {
        if ($number == 0) return '零';
        $units = ['', '万', '亿'];
        $result = '';
        $unitStack = [];

        while ($number > 0) {
            $part = $number % 10000;
            $number = (int)($number / 10000);
            $unit = array_shift($units);
            $unitStack[] = $unit;
            $result = self::convertFourDigits($part) . $unit . $result;
        }

        // 处理零
        $result = preg_replace('/零+/', '零', $result);
        $result = trim($result, '零');

        return $result ?: '';
    }

    private static function convertFourDigits($number)
    {
        static $cnDigits = ['', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
        static $cnUnits = ['', '拾', '佰', '仟'];

        $result = '';
        $number = str_pad($number, 4, '0', STR_PAD_LEFT);

        for ($i = 0; $i < 4; $i++) {
            $digit = $number[$i];
            $unit = $cnUnits[3 - $i];

            if ($digit == '0') {
                $result .= '零';
            } else {
                $result .= $cnDigits[$digit] . $unit;
            }
        }

        return preg_replace('/零+/', '零', $result);
    }

    private static function convertFraction($fraction)
    {
        $result = '';
        $digits = ['角', '分'];

        for ($i = 0; $i < 2; $i++) {
            $digit = $fraction[$i] ?? '0';
            if ($digit != '0') {
                $result .= self::convertDigit($digit) . $digits[$i];
            }
        }

        return $result ?: '整';
    }

    private static function convertDigit($digit)
    {
        $cnDigits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
        return $cnDigits[$digit];
    }
}
